import {getRequest} from "./api";

/**
 * 实例化菜单项并赋值给公共数据
 * @param router：VUE路由对象
 * @param store: 仓库(用于保存公共数据)
 */
export const initMenu = (router, store) => {
    //如果仓库的状态(state)中的全局变量routes(保存导航菜单公共数据)的长度大于0，说明有导航菜单数据，无需发送请求
    if (store.state.routes.length > 0) {
        return;
    }

    getRequest("/system/menuConfig/initMenu").then(data => {
        if (data) {
            let fmtRoutes = formatRoutes(data);//获取格式化菜单项数组
            router.addRoutes(fmtRoutes);//将格式化菜单项数组添加至VUE路由对象(动态导入VUE组件)
            store.commit('initRoutes', fmtRoutes);//将格式化菜单项添加在共享数据
            store.dispatch('connect');
        }
    })
}
/**
 * 格式化菜单项数据并添加至菜单项数组
 * @param routes：响应菜单项数据
 * @returns 格式化菜单项数组
 */
export const formatRoutes = (routes) => {
    let fmRoutes = [];
    routes.forEach(router => {
        //批量定义菜单项变量并赋值
        let {
            url,
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router;
        //如果包含子菜单属性并且子菜单属性类型为数组，进行递归调用
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        //格式化VUE路由对象
        let fmRouter = {
            url:url,
            path: path,
            name: name,
            iconCls: iconCls,
            meta: meta,
            children: children,
            component(resolve) {
                //使用require动态导入对应VUE组件对象(后端响应数据中component为字符串，此处应该拼接为VUE组件详细地址)
                if (component.startsWith("Home")) {
                    require(['../views/' + component + '.vue'], resolve);
                } else if (component.startsWith("Emp")) {
                    require(['../views/emp/' + component + '.vue'], resolve);
                } else if (component.startsWith("Per")) {
                    require(['../views/per/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sal")) {
                    require(['../views/sal/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sta")) {
                    require(['../views/sta/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sys")) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }
            }
        }
        fmRoutes.push(fmRouter);//菜单项格式化数组中添加格式化菜单项数据
    })
    return fmRoutes;//返回格式化菜单项数组
}